#include "logger.hh"
Logger *Logger::_pInstance = nullptr;
Category *Logger::_root = nullptr;
void Logger::warn(const char *file, int line, const char *func, const char *msg)
{
    if (_root->isPriorityEnabled(Priority::WARN))
    {
        _root->warnStream() << "[" << file << ":" << line << "][" << func << "]" << msg;
    }
}
void Logger::error(const char *file, int line, const char *func, const char *msg)
{
    if (_root->isPriorityEnabled(Priority::ERROR))
    {
        _root->errorStream() << "[" << file << ":" << line << "][" << func << "]" << msg;
    }
}
void Logger::debug(const char *file, int line, const char *func, const char *msg)
{
    if (_root->isPriorityEnabled(Priority::DEBUG))
    {
        _root->debugStream()<< "[" << file << ":" << line << "][" << func << "]" << msg;
    }
}
void Logger::info(const char *file, int line, const char *func, const char *msg)
{
    if (_root->isPriorityEnabled(Priority::INFO))
    {
        _root->infoStream() << "[" << file << ":" << line << "][" << func << "]" << msg;
    }
}

Logger *Logger::getInstance()
{
    if (_pInstance == NULL)
    {
        _pInstance = new Logger();
    }
    return _pInstance;
}

void Logger::destroy()
{
    if (_pInstance != NULL)
    {
        delete _pInstance;
        _pInstance = NULL;
    }
}
Logger::Logger()
{
    // 创建布局
    PatternLayout *p1 = new PatternLayout();
    p1->setConversionPattern("%d %c [%p] %m%n");
     PatternLayout *p2 = new PatternLayout();
    p1->setConversionPattern("%d %c [%p] %m%n");
     PatternLayout *p3 = new PatternLayout();
    p1->setConversionPattern("%d %c [%p] %m%n");
    // 创建输出器对象
    OstreamAppender *pos = new OstreamAppender("console", &cout);
    FileAppender *filepos = new FileAppender("file", "wd.log");
    RollingFileAppender *pos3 = new RollingFileAppender("rollingfile", "rolling.log", 5 * 1024, 3);
    pos->setLayout(p1);
    filepos->setLayout(p2);
    pos3->setLayout(p3);

    // 获取根日志记录器
    _root = &Category::getRoot();
    // 设置日志优先级
    _root->setPriority(Priority::INFO);
    _root->addAppender(pos);
    _root->addAppender(filepos);
    _root->addAppender(pos3);
}
Logger::~Logger()
{
    _root->removeAllAppenders();
    Category::shutdown();
}

int main()
{
    Logger::getInstance();
    LOG_INFO("应用程序启动");
    LOG_DEBUG("执行关键操作");
    LOG_ERROR("发生异常");
    LOG_WARN("有潜在问题");
    Logger::destroy();
    return 0;
}
